<?php

namespace app\admin\controller\sta;

use app\admin\model\Depot;
use app\admin\model\Factory;
use app\admin\model\Mafactory;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\response\Json;

/**
 * 物料库存汇总
 *  todo    其他报表01-物料库存汇总表
 * @icon fa fa-circle-o
 */
class Mstock extends Backend
{

    /**
     * Mstock模型对象
     * @var \app\admin\model\sta\Mstock
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\sta\Mstock;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    //      3.1     其他报表01-物料库存汇总表:  	生产入库单 - 不明

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //   全部批次为行,  条件是:   批次有出栏

//  TODO:  功能完成后, 需要改为: 查询完成上月的数据后,记录存到表 xxx, 并锁定数据不可修改
//  TODO:  查询条件:  月份,当月可修改;  (可能还会按厂区拆分)
        $infoModel = new \app\admin\model\m\Info;
        //  计算月份      *
        //   todo   需要改成可选月份
        //   查询本月数据是随动的,单条记录不可修改.  查询上月数据是已存到表 sta_material 的, 查询当月是即时的
        //   todo    $newdate  需要做成用户选择
        $newdate = date("Y-m-01");          // 月初       todo
        $newdate_31 = date("Y-m-d", strtotime("+1 month", strtotime($newdate) )  );    // 月底
        // 汇总月份
        $this->view->assign("mark", date("ym", strtotime($newdate) )."月" );

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        // 关联表查询
        $depotList = Depot::getList();
        $mafactoryList = Mafactory::getList();
        //$mcategoryList = Mcategory::getList();

//print_r($where);die;
        //  数据行:  物料信息,id 即是  m_info.id
        $list = $infoModel->where($where)
            ->field("*, unit as spec")
            ->order("id ASC")
            ->paginate($limit);
//echo Db::getLastSql();die;
        foreach($list as &$val){
            $val['depot_id'] = $depotList[$val['depot_id']];
            $val['mafactory_id'] = $mafactoryList[$val['mafactory_id']];

            // 计算月份
            $val['createtime'] = $newdate;           //  todo
        }

        //  上月期末库存   @wtt
        $lastData = $this->getLastStock($newdate);
//print_r($lastData);die;

        // TODO:  如果计算合计,  那么要按当前筛选条件, 进行`不分页` 计算
//print_r($list);die;
        // TODO:  采集对应数据

        foreach($list as &$val){
            // 领用数量
            $lingyong =  Db::name("m_apply")
                ->field("*, sum(num) as bill_num ")
                ->where('info_id', 'in' , $val['id'] )
                ->where('status', 'eq', '已通过'  )
                ->where('createtime' , 'between', [ $newdate, $newdate_31 ] )
                ->find();
            $lingyong_else =  Db::name("m_applyes")
                ->field("*, sum(num) as bill_num ")
                ->where('info_id', 'in' , $val['id'] )
                ->where('status', 'eq', '已通过'  )
                ->where('createtime' , 'between', [ $newdate, $newdate_31 ] )
                ->find();

            $buy =  Db::name("m_stockbill")
                ->field("*, sum(nums) as bill_num ")
                ->where('info_id', 'eq' , $val['id'] )
                ->where('status', 'eq', '已通过' )
                ->where('type', 'eq', '采购' )
                ->where('newdate' , 'between', [ $newdate, $newdate_31 ] )
                ->find();
            $diaobo =  Db::name("m_stockbill")
                ->field("*, sum(nums) as bill_num ")
                ->where('info_id', 'eq' , $val['id'] )
                ->where('status', 'eq', '已通过' )
                ->where('type', 'eq', '调拨' )
                ->where('newdate' , 'between', [ $newdate, $newdate_31 ] )
                ->find();

//echo Db::getLastSql();die;
            //  TODO        月初库存	 +采购单	 +调拨单	 -领用单	 -其他领用单	 +生产入库单	= 月末库存

            $val['a'] = isset($lastData[$val['id']]) ? $lastData[$val['id']]['o'] : 0 ;     //  月初库存        todo 上次月末库存
            $val['b'] = $buy    ? $buy['bill_num']    :0 ;              // 采购单
            $val['c'] = $diaobo ? $diaobo['bill_num'] :0 ;             //  调拨单

            $val['d'] = $lingyong ? $lingyong['bill_num'] :0;      //  领用单

            $val['f'] = $lingyong_else ? $lingyong_else['bill_num'] :0;      //  其他领用单
            $val['g'] = 0;      //  生产入库单

            $val['e'] = $val['a'] + $val['b'] +$val['c'] - $val['d'] - $val['f'] + $val['g'] ;      //  月末库存
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    //  获取上月月末库存
    public function getLastStock( $newdate ){
        // 上次结算的数据.     TODO  这里获取方法写的不准确,   do: 获取当前月份的前一次数据

        $date = date("Y-m", strtotime("-1 month", strtotime($newdate) )  );    // 月底
//print_r($date); die;
        $lastList = Db::name("sta_material")
            ->where("DATE_FORMAT(createtime,'%Y-%m')='{$date}' ")
            ->select();

        $lastArr = $lastList ;
        $lastData = array_column( $lastArr , null, 'info_id' );

        return $lastData ;
    }

}
